﻿using BCCommon;
using BCCommon.TMS.Transport;
using BCData.TMS.Agent.AgentRecord;
using BCData.TMS.VehicleTransportBusinessConfig;
using BCDto.Sim.Admin.Admin;
using BCDto.TMS.VehicleTransportBusinessConfig;
using BCEntity.Common.EntityNameConst;
using BCEntity.TMS.VehicleTransportBusinessConfig;
using BCService.Common.Area;
using BCService.TMS.Agent.AgentAreaRecord;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCService.TMS.VehicleTransportBusinessConfig
{
    public class VehicleTransportBusinessConfigService : IVehicleTransportBusinessConfigService
    {
        private readonly IVehicleTransportBusinessConfigData vehicleTransportBusinessConfigData;
        private readonly IVehicleTransportBusinessConfigOverwriteData vehicleTransportBusinessConfigOverwriteData;
        private readonly IAgentRecordData agentRecordData;
        private readonly IDatabaseContext databaseContext;
        private readonly IRedisService redisService;
        private readonly IZoneService zoneService;
        private readonly IAgentAreaRecordService agentAreaRecordService;
        private readonly string key = string.Format("{0}", EntityNameConst.VehicleTransportBusinessConfigEntity);

        public VehicleTransportBusinessConfigService(IVehicleTransportBusinessConfigData vehicleTransportBusinessConfigData,
            IVehicleTransportBusinessConfigOverwriteData vehicleTransportBusinessConfigOverwriteData,
            IAgentRecordData agentRecordData,
            IDatabaseContext databaseContext,
            IRedisService redisService,
            IZoneService zoneService,
            IAgentAreaRecordService agentAreaRecordService)
        {
            this.vehicleTransportBusinessConfigData = vehicleTransportBusinessConfigData;
            this.vehicleTransportBusinessConfigOverwriteData = vehicleTransportBusinessConfigOverwriteData;
            this.agentRecordData = agentRecordData;
            this.databaseContext = databaseContext;
            this.redisService = redisService;
            this.zoneService = zoneService;
            this.agentAreaRecordService = agentAreaRecordService;
        }

        public VehicleTransportBusinessConfigViewDto Create(AdminDto admin, VehicleTransportBusinessConfigRequestDto requestDto)
        {
            if (admin.AgentRecord != null)
            {
                throw new ArgumentException("您不是总公司员工，暂无权限添加");
            }
            var result = this.vehicleTransportBusinessConfigData.GetByTransportBusiness(requestDto.TransportBusiness).Result;
            if (result != null)
            {
                throw new ArgumentException("此运输业务已存在，不需重复添加");
            }
            if (string.IsNullOrWhiteSpace(requestDto.Remark))
            {
                throw new ArgumentException("业务描述不能为空");
            }
            result = this.vehicleTransportBusinessConfigData.Insert(new VehicleTransportBusinessConfigEntity()
            {
                TransportBusiness = requestDto.TransportBusiness.ToString(),
                Enabled = true,
                BusinessOrder = requestDto.BusinessOrder,
                Remark = requestDto.Remark,
                CreateAdminId = admin.AdminId,
                CreateAdminName = admin.FullName,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                EditAdminId = admin.AdminId,
                EditAdminName = admin.FullName
            }).GetAwaiter().GetResult();
            this.redisService.DeleteMultipleKey(key, false);
            return result.As<VehicleTransportBusinessConfigViewDto>();
        }

        public void Delete(AdminDto admin, int vehicleTransportBusinessConfigId)
        {
            if (admin.CompanyId == 1)
            {
                throw new ArgumentException("您不是总公司员工，暂无权限删除");
            }
            //如果是总部删除
            var result = this.vehicleTransportBusinessConfigData.GetEntity(vehicleTransportBusinessConfigId).Result;
            if (result == null)
            {
                throw new ArgumentException("车辆运输业务配置信息不存在");
            }
            var overwriteConfig = this.vehicleTransportBusinessConfigOverwriteData.GetEntityByConfigId(vehicleTransportBusinessConfigId).Result;
            if (overwriteConfig != null)
            {
                throw new ArgumentException("此业务已在代理商使用，不允许删除");
            }
            this.vehicleTransportBusinessConfigData.Delete(vehicleTransportBusinessConfigId).GetAwaiter().GetResult();
            this.redisService.DeleteMultipleKey(key, false);
        }

        public IEnumerable<VehicleTransportBusinessConfigDto> GetAllList(bool? enabled)
        {
            var result = this.redisService.TryGet(key, () =>
            {
                var configList = this.vehicleTransportBusinessConfigData.GetAllList(enabled).GetAwaiter().GetResult();
                return configList.As<IEnumerable<VehicleTransportBusinessConfigDto>>();
            }, TimeSpan.FromDays(1));
            return result;
        }

        public IEnumerable<VehicleTransportBusinessConfigViewDto> GetList(long? agentRecordId, string countyCode)
        {
            if (agentRecordId.HasValue)
            {
                string cacheKey = this.redisService.GetKey(key, countyCode, agentRecordId);
                var result = this.redisService.TryGet(cacheKey, () =>
                {
                    var configList = this.vehicleTransportBusinessConfigData.GetList().GetAwaiter().GetResult();
                    var configOverwriteList = this.vehicleTransportBusinessConfigOverwriteData.GetList(agentRecordId.Value, countyCode).GetAwaiter().GetResult();
                    List<VehicleTransportBusinessConfigViewEntity> viewList = new List<VehicleTransportBusinessConfigViewEntity>();
                    foreach (var item in configList)
                    {
                        if (configOverwriteList.Any(p => p.VehicleTransportBusinessConfigId == item.VehicleTransportBusinessConfigId))
                        {
                            var config = configOverwriteList.Single(p => p.VehicleTransportBusinessConfigId == item.VehicleTransportBusinessConfigId);
                            if (config.Enabled)
                            {
                                viewList.Add(item);
                            }
                        }
                        else if (item.Enabled)
                        {
                            viewList.Add(item);
                        }
                    }
                    return viewList.As<IEnumerable<VehicleTransportBusinessConfigViewDto>>();
                }, TimeSpan.FromDays(365));
                return result;
            }
            else
            {
                return this.GetList().As<IEnumerable<VehicleTransportBusinessConfigViewDto>>();
            }
        }

        public IEnumerable<VehicleTransportBusinessConfigDto> GetList()
        {
            var result = this.redisService.TryGet(key, () =>
            {
                var configList = this.vehicleTransportBusinessConfigData.GetList().GetAwaiter().GetResult();
                return configList.As<IEnumerable<VehicleTransportBusinessConfigDto>>();
            }, TimeSpan.FromDays(1));
            return result;
        }

        public PageableList<VehicleTransportBusinessConfigViewDto> Query(AdminDto admin, TransportBusinessType? transportBusiness, int pageIndex, int pageSize)
        {
            string cacheKey = this.redisService.GetKey(key, transportBusiness, pageIndex, pageSize);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var (data, dataCount) = this.vehicleTransportBusinessConfigData.Query(transportBusiness, pageIndex, pageSize).Result;
                return new PageableList<VehicleTransportBusinessConfigViewDto>()
                {
                    Count = dataCount,
                    Items = data.As<List<VehicleTransportBusinessConfigViewDto>>(),
                    PageIndex = pageIndex,
                    PageSize = pageSize
                };
            }, TimeSpan.FromDays(1));
            return result;
        }

        public VehicleTransportBusinessConfigViewDto Update(AdminDto admin, int vehicleTransportBusinessConfigId, VehicleTransportBusinessConfigPutDto putDto)
        {
            if (admin.CompanyId != 1)
            {
                throw new ArgumentException("非总公司员工无权修改此配置");
            }
            //如果是总部修改
            var result = this.vehicleTransportBusinessConfigData.GetEntity(vehicleTransportBusinessConfigId).Result;
            if (result == null)
            {
                throw new ArgumentException("车辆运输业务配置信息不存在");
            }
            if (string.IsNullOrWhiteSpace(putDto.Remark))
            {
                throw new ArgumentException("业务描述不能为空");
            }
            if (result.TransportBusiness == TransportBusinessType.SameCity.ToString())
            {
                if (!putDto.SameCityChargingMode.HasValue)
                {
                    throw new ArgumentException("同城计费模式不允许为空!");
                }
                if (putDto.SameCityChargingMode.Value == TransportSameCityChargingMode.EveryPointSurchargeAmount && !putDto.SameCityPointSurchargeAmount.HasValue)
                {
                    throw new ArgumentException("同城途经点串连计费模式时，同城途经点附加费金额为必填!");
                }
            }

            result.BusinessOrder = putDto.BusinessOrder;
            result.SameCityChargingMode = putDto.SameCityChargingMode?.ToString();
            result.SameCityPointSurchargeAmount = putDto.SameCityPointSurchargeAmount;
            result.Remark = putDto.Remark;
            result.UpdateTime = DateTime.Now;
            result.EditAdminId = admin.AdminId;
            result.EditAdminName = admin.FullName;
            this.vehicleTransportBusinessConfigData.Update(result).GetAwaiter().GetResult();
            this.redisService.DeleteMultipleKey(key, false);
            return result.As<VehicleTransportBusinessConfigViewDto>();
        }

        public VehicleTransportBusinessConfigDto UpdateEnabled(AdminDto admin, int vehicleTransportBusinessConfigId, bool enabled)
        {
            if (admin.CompanyId != 1)
            {
                throw new ArgumentException("非总公司员工无权修改此配置");
            }
            //如果是总部修改
            var result = this.vehicleTransportBusinessConfigData.GetEntity(vehicleTransportBusinessConfigId).Result;
            if (result == null)
            {
                throw new ArgumentException("车辆运输业务配置信息不存在");
            }
            result.Enabled = enabled;
            result.UpdateTime = DateTime.Now;
            result.EditAdminId = admin.AdminId;
            result.EditAdminName = admin.FullName;
            this.vehicleTransportBusinessConfigData.Update(result).GetAwaiter().GetResult();
            this.redisService.DeleteMultipleKey(key, false);
            return result.As<VehicleTransportBusinessConfigDto>();
        }
    }
}
